package Eclass.Score;

import java.util.List;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import login.UserModel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import Candidate.CandidateForm;
import Eclass.EclassForm;
import Forum.ForumThreadForm;
import Master.SchoolForm;

public class ScoreAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ScoreForm score = (ScoreForm) form;
		ScoreManager scoreManager = new ScoreManager();
		HttpSession session = request.getSession(true);
		UserModel user = (UserModel) session.getAttribute("userLogin");
		
		//-------------------------------------------------------------- Navigation ----------------------------------------------------------
				CandidateForm candidateForm = new CandidateForm();
				SchoolForm schoolForm = new SchoolForm();
				EclassForm eClassForm = new EclassForm();
				ForumThreadForm forumForm = new ForumThreadForm();
				//ScoreForm scoreForm = new ScoreForm();
				
				if("updateCandidate".equalsIgnoreCase(score.getTask())) {
					candidateForm.getcModel().setRegisNo("01-13-12- 029");
					candidateForm.setTask("update");
					return mapping.findForward("candidate");
				}else if("manageTrainee".equalsIgnoreCase(score.getTask())) {	
//					eClassForm.setTask("manageTrainee");
//					return mapping.findForward("eclass");
					candidateForm.setTask("manageTrainee");
					return mapping.findForward("candidate");
				}else if("batch".equalsIgnoreCase(score.getTask())) {
					eClassForm.setTask("batch");
					return mapping.findForward("eclass");
				}else if("listExamPrep".equalsIgnoreCase(score.getTask())) {
					eClassForm.setTask("listExamPrep");
					return mapping.findForward("eclass");
				}else if("manageSchool".equalsIgnoreCase(score.getTask())) {
					schoolForm.setTask("manageSchool");
					return mapping.findForward("master");
		  		}else if("forumPage".equalsIgnoreCase(score.getTask())) {
					forumForm.setTask("forumPage");
					return mapping.findForward("forum");
		  		}
//				}else if("report".equalsIgnoreCase(score.getTask())) {
//					scoreForm.setTask("report");
//					return mapping.findForward("score");
//				}
		//------------------------------------------------------------------------------------------------------------------------------
		
		if("listScore".equalsIgnoreCase(score.getTask())){
			if("admin".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getBatch());
				score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
			}else if("trainer".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getTrainerBatch(user.getUserid()));
				score.setListSubject(scoreManager.getTrainerSubject(user.getUserid()));
			}
			if(!"trainee".equalsIgnoreCase(user.getRole())){
				if("0".equals(score.getSearchSubject())){
					score.setListScore(scoreManager.getScoreList(score.getSearchBatch(), ""));
				}else {
					score.setListScore(scoreManager.getScoreList(score.getSearchBatch(), score.getSearchSubject()));
				}
			}else{
				score.setListScore(scoreManager.getScoreListForTrainee(user.getUserid()));
			}
			return mapping.findForward("manageScore");
		}
		if("insert".equalsIgnoreCase(score.getTask())){
//			score.setListBatch(scoreManager.getBatch());
//			score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
			if("admin".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getBatch());
				score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
			}else if("trainer".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getTrainerBatch(user.getUserid()));
				score.setListSubject(scoreManager.getTrainerSubject(user.getUserid()));
			}
			return mapping.findForward("insertScore");
		}
		if("showUpdateField".equalsIgnoreCase(score.getTask())){
			BatchModel batchModel= scoreManager.getBatchName(score.getSearchBatch());
			SubjectModel subjectModel = scoreManager.getSubjectName(score.getSearchSubject());
			ScoreModel scModel = scoreManager.getSessionDate(score.getSearchSession());
			score.setListScore(scoreManager.getScoreUpdateList(score.getSearchBatch(), score.getSearchSubject(),score.getSearchSession()));
			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			String append = null;
			String verified = null;
			if(score.getListScore().size()!=0){
				append = "<table>" +
							"<tr align='center'>" +
							"<td colspan='4'><b>" +
							batchModel.getBatchName()+" - "+ subjectModel.getClassName() + " - " + scModel.getStartDay() +
							"</b><br /><br /></td>" +
							"</tr>" +
						"</table>";
						
				append += "<table width='80%' class='boxShadow' border='0'>" +
						"<tr class='headerBox formHeaderBackground'>" +
						"<th class='formListStyle'></th>"+
						"<th class='formListStyle'>Name</th>"+
						"<th class='formListStyle'>Score</th>" +
						"<th class='formListStyle'>Status</th>"+
					 "</tr>";
			}
			else{
				append = "Data Not Found";
			}
			for(int i=0;i<score.getListScore().size();i++){
				ScoreModel scoreModel = (ScoreModel) score.getListScore().get(i);
				if(scoreModel.getScore()==null){
					scoreModel.setScore(0.0);
				}
				if("0".equals(scoreModel.getVerified())) {
					verified = "unverified";
				}else if(scoreModel.getVerified()==null) {
					verified = "unverified";
				}else {
					verified = "verified";
				}
				append += "<tr class='formListBackground'>" +
							"<td class='formListStyle'><input type='hidden' name='traineeId' value='"+scoreModel.getTraineeId()+"' /></td>" +
							"<td class='formListStyle'>"+scoreModel.getTraineeName()+"</td>" +
							"<td class='formListStyle'><input type='text' width='5px' name='score' value='"+scoreModel.getScore()+"' /></td>";
							if("unverified".equals(verified)){
								append += 
									"<td align='center' style='color: #E1292A;' class='formListStyle'>"+verified+"</td>" +
								"</tr>";
							}else{
								append += 
									"<td align='center' class='formListStyle'>"+verified+"</td>" +
								"</tr>";
				}
			}
			append+="<tr align='center' class='headerBox formHeaderBackground'>" +
						"<td colspan='2' class='formListStyle'>" +
							"<table title=\"update score\" class=\"buttonStyle\" style=\"cursor: pointer;\" onclick=\"javascript:updateScore();\">" +
								"<tr>" +
									"<td style=\"vertical-align: middle;\"><img src=\"images/saveButton.png\"/></td>" +
									"<td style=\"vertical-align: middle;\"><b>&nbsp;Save&nbsp;</b></td>" +
								"</tr>" +
							"</table>" +
						"</td>";
			if("admin".equalsIgnoreCase(user.getRole())){
				append +="<td colspan='1' class='formListStyle'>" +
							"<table title=\"verified\" class=\"buttonStyle\" style=\"cursor: pointer;\" onclick=\"javascript:verified();\">" +
								"<tr>" +
									"<td style=\"vertical-align: middle;\"><img src=\"images/checkButton.png\"/></td>" +
									"<td style=\"vertical-align: middle;\"><b>&nbsp;Verified&nbsp;</b></td>" +
								"</tr>" +
							"</table>" +
						"</td>";
				append +="<td colspan='1' class='formListStyle'>" +
							"<table title=\"cancel\" class=\"buttonStyle\" style=\"cursor: pointer;\" onclick=\"javascript:cancel();\">" +
								"<tr>" +
									"<td style=\"vertical-align: middle;\"><img src=\"images/cancelButton.png\"/></td>" +
									"<td style=\"vertical-align: middle;\"><b>&nbsp;Cancel&nbsp;</b></td>" +
								"</tr>" +
							"</table>" +
					    "</td>";
			}else {
				append +="<td colspan='2' class='formListStyle'>" +
							"<table title=\"cancel\" class=\"buttonStyle\" style=\"cursor: pointer;\" onclick=\"javascript:cancel();\">" +
								"<tr>" +
									"<td style=\"vertical-align: middle;\"><img src=\"images/cancelButton.png\"/></td>" +
									"<td style=\"vertical-align: middle;\"><b>&nbsp;Cancel&nbsp;</b></td>" +
								"</tr>" +
							"</table>" +
						"</td>";
			}
			append += "</tr>" +
					"</table>";
			
			out.println(append);
			out.flush();
			return null;
		}
		if("showUploadField".equalsIgnoreCase(score.getTask())){
			BatchModel batchModel= scoreManager.getBatchName(score.getSearchBatch());
			SubjectModel subjectModel = scoreManager.getSubjectName(score.getSearchSubject());
			ScoreModel scModel = scoreManager.getSessionDate(score.getSearchSession());
			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			String append = null;
			append = "<tr align='center'><td colspan='2'><b>" +
						batchModel.getBatchName()+" - "+ subjectModel.getClassName() + " - " + scModel.getStartDay() +
					"</b><br /><br /></td></tr>" +
					"<tr><td class=\"formListStyle\">" +
						"<input type='file' name='uploadFile'>" +
						"<table title=\"save\" class=\"buttonStyle\" style=\"cursor: pointer;\" onclick=\"javascript:uploadScore();\">" +
							"<tr>" +
								"<td style=\"vertical-align: middle;\"><img src=\"images/uploadButton.png\"/></td>" +
								"<td style=\"vertical-align: middle;\"><b>&nbsp;Upload&nbsp;</b></td>" +
							"</tr>" +
						"</table>" +
					"</td><td class=\"formListStyle\">" +
						"<table title=\"cancel\" class=\"buttonStyle\" style=\"cursor: pointer;\" onclick=\"javascript:cancel();\">" +
							"<tr>" +
								"<td style=\"vertical-align: middle;\"><img src=\"images/cancelButton.png\"/></td>" +
								"<td style=\"vertical-align: middle;\"><b>&nbsp;Cancel&nbsp;</b></td>" +
							"</tr>" +
						"</table>" +
					"</td></tr>";
			out.println(append);
			out.flush();
			return null;
		}
		if("showSessionCombo".equalsIgnoreCase(score.getTask())){
			if(score.getSearchSubject().length()!=0){
				score.setListSession(scoreManager.getSessionList(score.getSearchBatch(), score.getSearchSubject()));
				response.setContentType("text/text;charset=utf-8");
				response.setHeader("cache-control", "no-cache");
				PrintWriter out = response.getWriter();
				String append = null;
				if(score.getListSession().size()==0){
					append = "<option value='0'>No Session</option>";
				}
				for(int i=0;i<score.getListSession().size();i++){
					ScoreModel scoreModel = (ScoreModel) score.getListSession().get(i);
					append+="<option value='"+scoreModel.getClassSessionId()+"'>"+scoreModel.getStartDay()+"</option>";
				}
				out.println(append);
				out.flush();
				return null;
			}else {
				
			}
		}
		if("showSubjectCombo".equalsIgnoreCase(score.getTask())){
//			score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
//			response.setContentType("text/text;charset=utf-8");
//			response.setHeader("cache-control", "no-cache");
//			PrintWriter out = response.getWriter();
//			String append = null;
//			if(score.getListSubject().size()==0){
//				append = "<option value=''>No Subject</option>";
//			}
//			for(int i=0;i<score.getListSubject().size();i++){
//				SubjectModel subjectModel = (SubjectModel) score.getListSubject().get(i);
//				append+="<option value='"+subjectModel.getClassId()+"'>"+subjectModel.getClassName()+"</option>";
//			}
//			out.println(append);
//			out.flush();
//			return null;
			score.setListBatch(scoreManager.getBatch());
			score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
			return mapping.findForward("insertScore");
		}
		if("report".equalsIgnoreCase(score.getTask())){
			if("admin".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getBatch());
				score.setListSubject(scoreManager.getSubject(score.getBatchParam()));
				score.setListTrainee(scoreManager.getTraineeList(score.getSearchBatch()));
				score.setBatchChangeStatus("0");
			}else if("trainer".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getTrainerBatch(user.getUserid()));
				score.setListSubject(scoreManager.getTrainerSubject(user.getUserid()));
			}else{
//				HashMap map = new HashMap();
//				map.put("reportType", 2);
//				TraineeModel traineeModel = scoreManager.getTraineeName(user.getUserid());
//				map.put("traineeParam", scoreManager.getTraineeId(traineeModel.getTraineeNameList()).getTraineeId());
//				session.setAttribute("reportParam", map);
//				return mapping.findForward("reportPage");
				score.setListSubject(scoreManager.getSubject(scoreManager.getTraineeName(user.getUserid()).getBatchId().toString()));
			}
			return mapping.findForward("report");
		}
		if("showParamCombo".equalsIgnoreCase(score.getTask())){
			String reportType = score.getReportType();
			if("admin".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getBatch());
				score.setListSubject(scoreManager.getSubject(score.getBatchParam()));
				score.setListTrainee(scoreManager.getTraineeList(score.getBatchParam()));
			}else if("trainer".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getTrainerBatch(user.getUserid()));
				score.setListSubject(scoreManager.getTrainerSubject(user.getUserid()));
			}
			return mapping.findForward("report");
		}
		if("getReport".equalsIgnoreCase(score.getTask())){
			HashMap map = new HashMap();
			map.put("reportType", score.getReportType());
			map.put("batchParam", score.getBatchParam());
			if("trainee".equals(user.getRole())){
				map.put("traineeParam", scoreManager.getTraineeName(user.getUserid()).getTraineeId());
			}else{
				map.put("traineeParam", score.getTraineeParam());
			}
			map.put("subjectParam", score.getSubjectParam());
			map.put("batchTypeParam", score.getBatchTypeParam());
			session.setAttribute("reportParam", map);
			System.out.println(map);
			score.setListBatch(scoreManager.getBatch());
			score.setListSubject(scoreManager.getSubject(score.getBatchParam()));
			score.setListTrainee(scoreManager.getTraineeList(score.getBatchParam()));
			return mapping.findForward("reportPage");
		}
		if("viewGraph".equalsIgnoreCase(score.getTask())){
			HashMap map = new HashMap();
			map.put("reportType", score.getReportType());
			if("trainee".equals(user.getRole())){
				map.put("batchParam", scoreManager.getTraineeName(user.getUserid()).getBatchId());
				map.put("traineeParam", scoreManager.getTraineeName(user.getUserid()).getTraineeId());
			}else{
				map.put("traineeParam", score.getTraineeParam());
				map.put("batchParam", score.getBatchParam());
			}
			map.put("subjectParam", score.getSubjectParam());
			map.put("batchTypeParam", score.getBatchTypeParam());
			//System.out.println(score.getBatchTypeParam());
			session.setAttribute("reportParam", map);
			score.setListBatch(scoreManager.getBatch());
			score.setListSubject(scoreManager.getSubject(score.getBatchParam()));
			score.setListTrainee(scoreManager.getTraineeList(score.getBatchParam()));
			return mapping.findForward("graphPage");
		}
		if("updateScore".equalsIgnoreCase(score.getTask())){
			for (int i = 0; i < score.getScore().length; i++) {
				boolean result = scoreManager.updateScore(score.getSearchSession(), score.getTraineeId()[i], score.getScore()[i], user.getUserid());
				//setResult(result, "Update score", session);
				if(result){
					session.setAttribute("result", "Score updated succesfully. Score needs to be verified");
				}else{
					session.setAttribute("result", "Score updated failed.");
				}
			}
			score.setListBatch(scoreManager.getBatch());
			score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
			return mapping.findForward("insertScore");
		}
		if("verified".equalsIgnoreCase(score.getTask())){
			for (int i = 0; i < score.getScore().length; i++) {
				boolean result = scoreManager.verifiedScore(score.getSearchSession(), score.getTraineeId()[i]);
				setResult(result, "Score verify", session);
			}
			ScoreModel scoreModel = scoreManager.checkSessionScore(score.getSearchBatch(), score.getSearchSubject());
			String checkSessionScore = scoreModel.getFlagCheckScore();
			if("1".equals(checkSessionScore)){
				for (int i = 0; i < score.getScore().length; i++) {
					scoreManager.calculateClassScore(score.getSearchSession(), score.getTraineeId()[i]);
				}
				scoreModel = scoreManager.getBatchClassId(score.getSearchSession());
				boolean result = scoreManager.calculateGrade(scoreModel.getBatchClassId());
				setResult(result, "Score verified and class score updated", session);
			}
			score.setListBatch(scoreManager.getBatch());
			score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
			score.setListScore(scoreManager.getScoreList(score.getSearchBatch(), score.getSearchSubject()));
			return mapping.findForward("manageScore");
		}
		if("uploadScore".equalsIgnoreCase(score.getTask())){
			FormFile myFile = score.getUploadFile();
			String fileName = score.getFileName();
			String directoryPath = "tesUploadFile\\ExamQuestions\\";
			String filePath = getServlet().getServletContext().getRealPath("/")
					+ directoryPath;
			
			if(!"".equals(fileName)){
				File fileToCreate = new File(filePath, fileName);
				if (!fileToCreate.exists()) {
					FileOutputStream fileOutStream = new FileOutputStream(
							fileToCreate);
					fileOutStream.write(myFile.getFileData());
					fileOutStream.flush();
					fileOutStream.close();
				}
			}
			String fullFilePath = filePath + fileName;
			request.setAttribute("directoryPath", directoryPath);
			request.setAttribute("fileName", fileName);
			
			List sheetData = new ArrayList();
			sheetData = ScoreImport.ScoreCheck(fullFilePath);
			String traineeName = null;
			Double traineeScore = null;
			List firstRow = (List) sheetData.get(0);
			Cell cellTrainee = (Cell) firstRow.get(0);
			Cell cellScore = (Cell) firstRow.get(1);
			if(!"Trainee".equalsIgnoreCase(cellTrainee.toString()) && "Score".equalsIgnoreCase(cellScore.toString())){
				session.setAttribute("result", "Excel format data not appropriate");
			}else{
			for (int i = 1; i < sheetData.size(); i++) {
				List data = (List) sheetData.get(i);
				//System.out.println(data);
				for (int j = 0; j < data.size(); j++) {
					Cell cell = (Cell) data.get(j);
					//System.out.println(cell);
					if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
						//System.out.println(cell);
						traineeName = cell.toString();
					}else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
						traineeScore = cell.getNumericCellValue();
					}
				}
				if(traineeName.contains(" ")){
					traineeName = traineeName.replaceAll(" ", "");
				}
				TraineeModel traineeModel = scoreManager.getTraineeId(traineeName.toLowerCase());
				boolean result = scoreManager.updateScore(score.getSearchSession(), traineeModel.getTraineeId(), traineeScore, user.getUserid());
				//setResult(result, "Upload score", session);
				if(result){
					session.setAttribute("result", "Score uploaded succesfully. Score needs to be verified");
				}else{
					session.setAttribute("result", "Score upload failed.");
				}
			}
			}
			File excelFile = new File(fullFilePath);
			excelFile.delete();
			score.setListBatch(scoreManager.getBatch());
			score.setListSubject(scoreManager.getSubject(score.getSearchBatch()));
			return mapping.findForward("insertScore");
		}
		else{
			if("admin".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getBatch());
				score.setListSubject(scoreManager.getSubject(scoreManager.getLastBatch().getBatchId()));
			}else if("trainer".equalsIgnoreCase(user.getRole())){
				score.setListBatch(scoreManager.getTrainerBatch(user.getUserid()));
				score.setListSubject(scoreManager.getTrainerSubject(user.getUserid()));
			}
			if(!"trainee".equalsIgnoreCase(user.getRole())){
				score.setListScore(scoreManager.getScoreList(scoreManager.getLastBatch().getBatchId(), score.getSearchSubject()));
			}else{
				score.setListScore(scoreManager.getScoreListForTrainee(user.getUserid()));
			}
			
			return mapping.findForward("manageScore");
		}
	}
	
	public void setResult(boolean result, String action, HttpSession session){
		String resultText = "";
		if(result){
			resultText = action + " successfully.";
		}else{
			resultText = action + " failed.";
		}
		session.setAttribute("result", resultText);
	}
}
